#ifndef XLCOMM_NET_TIMER_H_
#define XLCOMM_NET_TIMER_H_

#include <atomic>

#include "xlcomm/base/date_time.h"
#include "xlcomm/net/callbacks.h"
#include "xlcomm/noncopyable.h"

namespace xlcomm {
namespace net {

// 定时器事件
class Timer : noncopyable {
 public:
  Timer(TimerCallback cb, Timestamp when_expire, double interval_second)
      : callback_(std::move(cb)),
        when_expire_(when_expire),
        interval_second_(interval_second),
        repeat_(interval_second > 0.0),
        sequence_(++num_created_) {}

  // 运行回调函数
  void Run() const {
    if (callback_) callback_();
  }

  // 以now + interval_second_重新设置 when_expire_
  void Reset(Timestamp now);

  Timestamp when_expire() const { return when_expire_; }
  bool repeat() const { return repeat_; }
  int64_t sequence() const { return sequence_; }

 private:
  const TimerCallback callback_;
  Timestamp when_expire_;
  const double interval_second_;
  const bool repeat_;
  const int64_t sequence_;

  static std::atomic<int64_t> num_created_;
};

}  // namespace net
}  // namespace xlcomm

#endif  // XLCOMM_NET_TIMER_H_
